package pit.com.ordermobilesystem.provider;

import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

public abstract class BaseProvider extends ContentProvider{
	
	
	
	public static ContentValues getContentValues(Context mContext, JSONObject json) throws JSONException {
		ContentValues values = new ContentValues();
	    Iterator<String> iter = json.keys();
	    while (iter.hasNext()) {
	      String key = iter.next();
	      try {
	        Object value = json.get(key);
	        if(value==null || value.toString().equals("null")){
	        	values.put(key,"");
	        }else
	        values.put(key, value.toString());
	      } catch (JSONException e) {
	      }
	    }
		return values;
	}
	
	public static ContentValues getContentValues(Context mContext, Cursor cursor)  {
		ContentValues values = new ContentValues();
		for(String columnName:cursor.getColumnNames()){
			int columnIndex=cursor.getColumnIndex(columnName);
			int type=cursor.getType(columnIndex);
			switch (type) {
				case Cursor.FIELD_TYPE_INTEGER:
					values.put(columnName, cursor.getInt(columnIndex));
					break;
				case Cursor.FIELD_TYPE_STRING:
					values.put(columnName, cursor.getString(columnIndex));
					break;
				default:
					break;
			}
		}
		return values;
	}
	
	public static JSONObject getJsonObjectFromCursor(Cursor cursor) throws JSONException {
		       JSONObject jsonObject=new JSONObject();
		       for(int i=0;i<cursor.getColumnCount();i++){
		    	  String columnName= cursor.getColumnName(i);

		    	  if(cursor.getType(i)==Cursor.FIELD_TYPE_INTEGER){
		    		  jsonObject.put(columnName, cursor.getLong(i));
		    	  }else{
		    		  jsonObject.put(columnName, cursor.getString(i));
		    	  }
		       }
		        return jsonObject;
	}
	
	public static JSONArray getJSONArrayFromCursor(Cursor cursor) throws JSONException{
		JSONArray array=new JSONArray();
		if(cursor!=null){
			while(cursor.moveToNext()){
				JSONObject object=getJsonObjectFromCursor(cursor);
				array.put(object);
			}
		}
		return array;
		
	}
}
